﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.IO;
using System.Xml;
using System.Windows.Forms;
using log4net;
using MPMovieCatalog.Configuration;
using MPMovieCatalog.Domain;
using MPMovieCatalog.Forms;
using MPMovieCatalog.Service;
using MPMovieCatalog.Util;

namespace MPMovieCatalog.Export.Forms
{
    public partial class HTMLExportForm : Form
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(HTMLExportForm));

        private List<RadioButton> m_moviesButtonGroup = new List<RadioButton>();
        private List<RadioButton> m_listTypeButtonGroup = new List<RadioButton>();
        private List<RadioButton> m_indexTypeButtonGroup = new List<RadioButton>();
        private List<RadioButton> m_customLayoutTypeButtonGroup = new List<RadioButton>();

        private Dictionary<string, FontFamily> families = new Dictionary<string, FontFamily>();

        public HTMLExportForm()
        {
            InitializeComponent();
            UpdateUI();

            m_moviesButtonGroup.Add(allMoviesRadioButton);
            m_moviesButtonGroup.Add(selectedMoviesRadioButton);

            m_listTypeButtonGroup.Add(singleListRadioButton);
            m_listTypeButtonGroup.Add(firstLetterRadioButton);
            m_listTypeButtonGroup.Add(pagedListRadioButton);

            m_indexTypeButtonGroup.Add(customizeIndexTemplateRadioButton);
            m_indexTypeButtonGroup.Add(selectIndexTemplateRadioButton);

            m_customLayoutTypeButtonGroup.Add(customListLayoutRadioButton);
            m_customLayoutTypeButtonGroup.Add(customThumbLayoutRadioButton);
        }

        public ArrayList SelectedMovies { get; set; }

        public long AllMoviesCount { get; set; }

        private void TextExportForm_Load(object sender, EventArgs e)
        {
            foreach (FontFamily fontFamily in FontFamily.Families)
            {
                fontComboBox.Items.Add(fontFamily.Name);
                families[fontFamily.Name] = fontFamily;
            }

            ConfigurationWrapper wrapper = new ConfigurationWrapper();
            SetSelectedIndex(m_moviesButtonGroup, wrapper.HTMLExportSection.Movies);
            SetSelectedIndex(m_listTypeButtonGroup, wrapper.HTMLExportSection.ListType);
            SetSelectedIndex(m_indexTypeButtonGroup, wrapper.HTMLExportSection.IndexType);
            SetSelectedIndex(m_customLayoutTypeButtonGroup, wrapper.HTMLExportSection.CustomLayoutType);

            itemsPerPageUpDown.Value = wrapper.HTMLExportSection.ItemsPerPage;
            itemsPerPageUpDown.Enabled = (((HtmlListType)wrapper.HTMLExportSection.ListType) == HtmlListType.Paged);
            folderTextBox.Text = wrapper.HTMLExportSection.Folder;
            indexFileNameTextBox.Text = wrapper.HTMLExportSection.IndexFileName;
            overwriteCheckBox.Checked = wrapper.HTMLExportSection.OverwriteFiles;
            openIndexPageCheckBox.Checked = wrapper.HTMLExportSection.OpenIndexPage;

            indexTitleTextBox.Text = wrapper.HTMLExportSection.IndexTtitle;
            customizeIndexTemplateGroupBox.Enabled = customizeIndexTemplateRadioButton.Checked;
            fontComboBox.SelectedItem = wrapper.HTMLExportSection.FontName;
            fontSizeUpDown.Value = wrapper.HTMLExportSection.FontSize;
            fontColorPanel.BackColor = ColorTranslator.FromHtml(wrapper.HTMLExportSection.FontColor);
            backColorPanel.BackColor = ColorTranslator.FromHtml(wrapper.HTMLExportSection.BackColor);
            thumbSizeUpDown.Value = wrapper.HTMLExportSection.ThumbSize;
            includeCreationDateCheckBox.Checked = wrapper.HTMLExportSection.IncludeCreationDate;
            customListLayoutGroupBox.Enabled = customListLayoutRadioButton.Checked;
            shadingCheckBox.Checked = wrapper.HTMLExportSection.ShadingEnabled;
            thumbCheckBox.Checked = wrapper.HTMLExportSection.ShowThumb;
            customThumbLayoutGroupBox.Enabled = customThumbLayoutRadioButton.Checked;
            columnsUpDown.Value = wrapper.HTMLExportSection.ColumnsCount;
            thumbBackgroundPanel.BackColor = ColorTranslator.FromHtml(wrapper.HTMLExportSection.ThumbBackColor);
            showDescriptionCheckBox.Checked = wrapper.HTMLExportSection.ShowDescription;

            indexTemplateComboBox.DataSource = TemplateUtils.FindAllTemplates(TemplateType.ExportIndex, true);
            indexTemplateComboBox.SelectedItem = TemplateUtils.FindTemplateByTypeAndName(TemplateType.ExportIndex, wrapper.HTMLExportSection.IndexTemplate);
            indexTemplateComboBox.Enabled = !customizeIndexTemplateRadioButton.Checked;

            createDetailsCheckBox.Checked = wrapper.HTMLExportSection.CreateDetails;
            detailsTemplateComboBox.DataSource = TemplateUtils.FindAllTemplates(TemplateType.ExportDetails, true);
            detailsTemplateComboBox.SelectedItem = TemplateUtils.FindTemplateByTypeAndName(TemplateType.ExportDetails, wrapper.HTMLExportSection.DetailsTemplate);
            detailsTemplateComboBox.Enabled = createDetailsCheckBox.Checked;

            allMoviesRadioButton.Text = string.Format(ResourceUtils.GetString("export", 1), AllMoviesCount);
            selectedMoviesRadioButton.Text = string.Format(ResourceUtils.GetString("export", 2), SelectedMovies == null ? 0 : SelectedMovies.Count);
        }

        private void browseButton_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog(this) == DialogResult.OK)
            {
                folderTextBox.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void fieldsButton_Click(object sender, EventArgs e)
        {
            using (FieldsForm fieldsForm = new FieldsForm())
            {
                ConfigurationWrapper wrapper = new ConfigurationWrapper();
                fieldsForm.SelectedFields = wrapper.HTMLExportSection.Fields;

                if (fieldsForm.ShowDialog(this) == DialogResult.OK)
                {
                    wrapper.HTMLExportSection.Fields = fieldsForm.SelectedFields;
                    wrapper.SaveConfiguration();
                }
            }
        }

        private void TextExportForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            ConfigurationWrapper wrapper = new ConfigurationWrapper();
            wrapper.HTMLExportSection.Movies = GetSelectedIndex(m_moviesButtonGroup);
            wrapper.HTMLExportSection.ListType = GetSelectedIndex(m_listTypeButtonGroup);
            wrapper.HTMLExportSection.ItemsPerPage = int.Parse(itemsPerPageUpDown.Value.ToString()); ;
            wrapper.HTMLExportSection.Folder = folderTextBox.Text;
            wrapper.HTMLExportSection.IndexFileName = indexFileNameTextBox.Text;
            wrapper.HTMLExportSection.OverwriteFiles = overwriteCheckBox.Checked;
            wrapper.HTMLExportSection.OpenIndexPage = openIndexPageCheckBox.Checked;

            wrapper.HTMLExportSection.IndexTtitle = indexTitleTextBox.Text;
            wrapper.HTMLExportSection.IndexType = GetSelectedIndex(m_indexTypeButtonGroup);

            if (fontComboBox.SelectedItem != null)
            {
                wrapper.HTMLExportSection.FontName = fontComboBox.SelectedItem as string;
            }
            wrapper.HTMLExportSection.FontSize = fontSizeUpDown.Value;
            wrapper.HTMLExportSection.FontColor = ColorTranslator.ToHtml(fontColorPanel.BackColor);
            wrapper.HTMLExportSection.BackColor = ColorTranslator.ToHtml(backColorPanel.BackColor);
            wrapper.HTMLExportSection.ThumbSize = thumbSizeUpDown.Value;
            wrapper.HTMLExportSection.IncludeCreationDate = includeCreationDateCheckBox.Checked;
            wrapper.HTMLExportSection.CustomLayoutType = GetSelectedIndex(m_customLayoutTypeButtonGroup);
            wrapper.HTMLExportSection.ShadingEnabled = shadingCheckBox.Checked;
            wrapper.HTMLExportSection.ShowThumb = thumbCheckBox.Checked;
            wrapper.HTMLExportSection.ColumnsCount = columnsUpDown.Value;
            wrapper.HTMLExportSection.ThumbBackColor = ColorTranslator.ToHtml(thumbBackgroundPanel.BackColor);
            wrapper.HTMLExportSection.ShowDescription = showDescriptionCheckBox.Checked;

            if (indexTemplateComboBox.SelectedItem != null)
            {
                wrapper.HTMLExportSection.IndexTemplate = ((Template)indexTemplateComboBox.SelectedItem).Name;
            }

            wrapper.HTMLExportSection.CreateDetails = createDetailsCheckBox.Checked;
            if (detailsTemplateComboBox.SelectedItem != null)
            {
                wrapper.HTMLExportSection.DetailsTemplate = ((Template)detailsTemplateComboBox.SelectedItem).Name;
            }

            wrapper.SaveConfiguration();
        }

        private void SetSelectedIndex(List<RadioButton> buttonGroup, int index)
        {
            if (index >= 0 && index < buttonGroup.Count)
            {
                for (int i = 0; i < buttonGroup.Count; i++)
                {
                    buttonGroup[i].Checked = (i == index);
                }
            }
        }

        private int GetSelectedIndex(List<RadioButton> buttonGroup)
        {
            int index = -1;
            foreach (RadioButton radioButton in buttonGroup)
            {
                if (radioButton.Checked)
                {
                    index = buttonGroup.IndexOf(radioButton);
                }
            }
            return index;
        }

        private void exportButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(folderTextBox.Text))
            {
                MessageBox.Show(this, ResourceUtils.GetString("export", 8), ResourceUtils.GetString("common", 3), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                folderTextBox.Focus();
                return;
            }

            ArrayList ids = null;
            if (selectedMoviesRadioButton.Checked)
            {
                ids = new ArrayList();
                if (SelectedMovies != null && SelectedMovies.Count > 0)
                {
                    foreach (MovieInfo movieInfo in SelectedMovies)
                    {
                        ids.Add(movieInfo.Id);
                    }
                }
                else
                {
                    ids.Add(0);
                }
            }
            ArrayList movies = MovieServiceFactory.getMovieService().FindMovieInfoByIds(ids);

            Template indexTemplate = null;
            int thumbSize = 200;
            Dictionary<string, object> parameters = null;
            if (customizeIndexTemplateRadioButton.Checked)
            {
                thumbSize = (int) thumbSizeUpDown.Value;

                parameters = new Dictionary<string, object>();
                parameters.Add("includeCreationDate", includeCreationDateCheckBox.Checked);

                Dictionary<string, string> styleParams = new Dictionary<string, string>();
                styleParams.Add("FONTNAME", fontComboBox.SelectedItem.ToString());
                styleParams.Add("FONTSIZE", fontSizeUpDown.Value.ToString());
                styleParams.Add("FONTCOLOR", ColorTranslator.ToHtml(fontColorPanel.BackColor));
                styleParams.Add("BGCOLOR", ColorTranslator.ToHtml(backColorPanel.BackColor));

                if (customThumbLayoutRadioButton.Checked)
                {
                    styleParams.Add("THUMBBGCOLOR", ColorTranslator.ToHtml(thumbBackgroundPanel.BackColor));
                    string style = TemplateUtils.PrepareTemplate("exportthumbindex_template.css", styleParams);

                    Dictionary<string, string> templateParams = new Dictionary<string, string>();
                    templateParams.Add("EXPORTSTYLE", style);

                    string templateString = TemplateUtils.PrepareTemplate("exportthumbindex_template.xsl", templateParams);
                    indexTemplate = new Template(templateString);

                    parameters.Add("indexTableCols", columnsUpDown.Value);
                    parameters.Add("thumbShowCaption", showDescriptionCheckBox.Checked);
                }
                else
                {
                    string style = TemplateUtils.PrepareTemplate("exportindex_template.css", styleParams);

                    StringBuilder headerBuilder = new StringBuilder();
                    StringBuilder bodyBuilder = new StringBuilder();
                    ConfigurationWrapper wrapper = new ConfigurationWrapper();
                    foreach (Field field in wrapper.HTMLExportSection.Fields)
                    {
                        headerBuilder.AppendLine(field.TemplateHeader);
                        bodyBuilder.AppendLine(field.TemplateValue);
                    }

                    Dictionary<string, string> templateParams = new Dictionary<string, string>();
                    templateParams.Add("EXPORTSTYLE", style);
                    templateParams.Add("HEADERDATA", headerBuilder.ToString());
                    templateParams.Add("BODYDATA", bodyBuilder.ToString());

                    string templateString = TemplateUtils.PrepareTemplate("exportindex_template.xsl", templateParams);
                    indexTemplate = new Template(templateString);

                    parameters.Add("thumbnails", thumbCheckBox.Checked);
                    parameters.Add("shading", shadingCheckBox.Checked);
                }
            }
            else
            {
                indexTemplate = indexTemplateComboBox.SelectedItem as Template;
            }

            HtmlExporter htmlExporter = new HtmlExporter(movies, (HtmlListType)GetSelectedIndex(m_listTypeButtonGroup), 12, folderTextBox.Text, indexFileNameTextBox.Text, overwriteCheckBox.Checked, indexTitleTextBox.Text, indexTemplate, createDetailsCheckBox.Checked ? detailsTemplateComboBox.SelectedItem as Template : null, thumbSize, parameters);
            using (ProgressWorker progressWorker = new ProgressWorker(htmlExporter))
            {
                progressWorker.Start();
            }

            if (openIndexPageCheckBox.Checked)
            {
                string indexPath = folderTextBox.Text + @"\" + indexFileNameTextBox.Text;
                try
                {
                    Process.Start(indexPath);
                }
                catch (System.Exception ex)
                {
                    log.Error(string.Format("Error opening file: {0}, message: {1}", indexPath, ex.Message), ex);
                }
            }


            DialogResult = DialogResult.OK;
            Close();
        }

        private void UpdateUI()
        {
            this.Text = ResourceUtils.GetString("htmlExport", 0);
            generalTabPage.Text = ResourceUtils.GetString("htmlExport", 1);
            listTypeGroupBox.Text = ResourceUtils.GetString("htmlExport", 2);
            singleListRadioButton.Text = ResourceUtils.GetString("htmlExport", 3);
            firstLetterRadioButton.Text = ResourceUtils.GetString("htmlExport", 4);
            pagedListRadioButton.Text = ResourceUtils.GetString("htmlExport", 5);
            itemsPerPageLabel.Text = ResourceUtils.GetString("htmlExport", 6);
            destinationGroupBox.Text = ResourceUtils.GetString("htmlExport", 7);
            folderLabel.Text = ResourceUtils.GetString("htmlExport", 8);
            browseButton.Text = ResourceUtils.GetString("htmlExport", 9);
            indexFilenameLabel.Text = ResourceUtils.GetString("htmlExport", 10);
            overwriteCheckBox.Text = ResourceUtils.GetString("htmlExport", 11);
            openIndexPageCheckBox.Text = ResourceUtils.GetString("htmlExport", 12);
            indexTemplateTabPage.Text = ResourceUtils.GetString("htmlExport", 13);
            indexTitleLabel.Text = ResourceUtils.GetString("htmlExport", 14);
            customizeIndexTemplateRadioButton.Text = ResourceUtils.GetString("htmlExport", 15);
            fontLabel.Text = ResourceUtils.GetString("htmlExport", 16);
            fontSizeLabel.Text = ResourceUtils.GetString("htmlExport", 17);
            fontColorLabel.Text = ResourceUtils.GetString("htmlExport", 18);
            backColorLabel.Text = ResourceUtils.GetString("htmlExport", 19);
            thumbSizeLabel.Text = ResourceUtils.GetString("htmlExport", 20);
            thumbSizeLabel2.Text = ResourceUtils.GetString("htmlExport", 21);
            includeCreationDateCheckBox.Text = ResourceUtils.GetString("htmlExport", 22);
            customListLayoutRadioButton.Text = ResourceUtils.GetString("htmlExport", 23);
            shadingCheckBox.Text = ResourceUtils.GetString("htmlExport", 24);
            thumbCheckBox.Text = ResourceUtils.GetString("htmlExport", 25);
            fieldsButton.Text = ResourceUtils.GetString("htmlExport", 26);
            customThumbLayoutRadioButton.Text = ResourceUtils.GetString("htmlExport", 27);
            columnsCountLabel.Text = ResourceUtils.GetString("htmlExport", 28);
            thumbBackgroundLabel.Text = ResourceUtils.GetString("htmlExport", 29);
            showDescriptionCheckBox.Text = ResourceUtils.GetString("htmlExport", 30);
            selectIndexTemplateRadioButton.Text = ResourceUtils.GetString("htmlExport", 31);
            detailsTemplateTabPage.Text = ResourceUtils.GetString("htmlExport", 32);
            createDetailsCheckBox.Text = ResourceUtils.GetString("htmlExport", 33);
            selectDetailTemplateLabel.Text = ResourceUtils.GetString("htmlExport", 34);

            moviesGroupBox.Text = ResourceUtils.GetString("export", 0);
            allMoviesRadioButton.Text = ResourceUtils.GetString("export", 1);
            selectedMoviesRadioButton.Text = ResourceUtils.GetString("export", 2);
            exportButton.Text = ResourceUtils.GetString("export", 3);
            cancelButton.Text = ResourceUtils.GetString("export", 4);
        }

        private void customizeIndexTemplateRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            customizeIndexTemplateGroupBox.Enabled = customizeIndexTemplateRadioButton.Checked;
            indexTemplateComboBox.Enabled = !customizeIndexTemplateRadioButton.Checked;

        }

        private void createDetailsCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            detailsTemplateComboBox.Enabled = createDetailsCheckBox.Checked;
        }

        private void pagedListRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            itemsPerPageUpDown.Enabled = pagedListRadioButton.Checked;
        }

        private void fontComboBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();

            if (e.Index >= 0)
            {
                System.Drawing.Font font = e.Font;

                FontFamily fontFamily = families[fontComboBox.Items[e.Index] as string];
                if (fontFamily.IsStyleAvailable(FontStyle.Regular))
                {
                    font = new Font(fontFamily, e.Font.Size);
                }
                else if (fontFamily.IsStyleAvailable(FontStyle.Bold))
                {
                    font = new Font(fontFamily, e.Font.Size, FontStyle.Bold);
                }
                else if (fontFamily.IsStyleAvailable(FontStyle.Italic))
                {
                    font = new Font(fontFamily, e.Font.Size, FontStyle.Italic);
                }

                e.Graphics.DrawString(fontFamily.Name, font, new SolidBrush(e.ForeColor), e.Bounds);
            }

            e.DrawFocusRectangle();
        }

        private void fontColorButton_Click(object sender, EventArgs e)
        {
            colorDialog.Color = fontColorPanel.BackColor;
            if (colorDialog.ShowDialog(this) == DialogResult.OK)
            {
                fontColorPanel.BackColor = colorDialog.Color;
            }
        }

        private void backColorButton_Click(object sender, EventArgs e)
        {
            colorDialog.Color = backColorPanel.BackColor;
            if (colorDialog.ShowDialog(this) == DialogResult.OK)
            {
                backColorPanel.BackColor = colorDialog.Color;
            }
        }

        private void customListLayoutRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            customListLayoutGroupBox.Enabled = customListLayoutRadioButton.Checked;
            customThumbLayoutGroupBox.Enabled = !customListLayoutRadioButton.Checked;
        }

        private void thumbBackgroundButton_Click(object sender, EventArgs e)
        {
            colorDialog.Color = thumbBackgroundPanel.BackColor;
            if (colorDialog.ShowDialog(this) == DialogResult.OK)
            {
                thumbBackgroundPanel.BackColor = colorDialog.Color;
            }
        }
    }
}
